package top.sinfonia.demo.elasticsearch.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.sinfonia.demo.elasticsearch.po.User;
import top.sinfonia.demo.elasticsearch.repository.UserElasticsearchRepository;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author singoasher
 * @date 2018/4/25
 */
@Service
public class UserService {
    private UserElasticsearchRepository userElasticsearchRepository;

    @Autowired
    public UserService(UserElasticsearchRepository userElasticsearchRepository) {
        this.userElasticsearchRepository = userElasticsearchRepository;
    }

    public User create(String name, String remark) {
        User user = new User();
        user.setName(name);
        user.setRemark(remark);
        return userElasticsearchRepository.save(user);
    }

    public User createOrUpdate(String id, String name, String remark) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setRemark(remark);
        return userElasticsearchRepository.save(user);
    }

    public User get(String id) {
        return userElasticsearchRepository.findById(id).orElse(null);
    }

    public List<User> list() {
        return StreamSupport.stream(userElasticsearchRepository.findAll().spliterator(), true)
                .collect(Collectors.toList());
    }
}
